package com.example.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author lei yu
 * @date 2024/05/15
 */
public class DBUtils {
    static Properties properties;
    static {
        properties = new Properties();
        try {
            InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(inputStream);
            Class.forName(properties.getProperty("driverClass"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(
                properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
    }
    public static void closeAll(Connection connection, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            System.out.println("msg = " + e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException, SQLException {
        Connection connection = getConnection();
        closeAll(connection, null, null);
    }
}
